import { ActionKey } from "@/action/ActionKey";
import { actionManager } from "@/action/ActionManager";
import { MetaclassType } from "@/constants/MetaclassType";
import { CreatePropertyModelTreeSelect } from "@/modules/model/actions/project/CreatePropertyModelTreeSelect";
import { modelService } from "@/modules/model/service";
import { LegendItem } from "../types";
import { PaneModel } from "./PaneModel";
import { StType } from "@/constants/StType";
import { propertyUtil } from "../PropertyUtil";
import { PropertyDataType, PropertyKey } from "@/constants/Enums";
import { loading } from "@/common/Loading";

export class LegendPaneModel extends PaneModel {
  tableData: LegendItem[] = [];
  searchActive = false;
  sortByNameActive = false;
  searchQuery = "";

  currentRow: LegendItem | null = null;

  addLoading = false;
  copyLoading = false;
  deleteLoading = false;

  columns = [
    { label: "名称", width: 110, prop: "name" },
    { label: "legendStyle", width: 110, prop: "adornment" },
    { label: "指定元素", width: 110, prop: "elements" },
    { label: "匹配条件", width: 110, prop: "condition" },
    { label: "优先级", width: 110, prop: "priority" }
  ];

  async loadData() {
    const { projectId, modelId } = this.tabsModel.data;
    if (!projectId || !modelId) return;
    this.loading = true;
    this.tableData = await modelService.getLegendItemBasicData(projectId, modelId).finally(() => {
      this.loading = false;
    });
    for (let i = 0; i < this.tableData.length; i++) {
      const element = this.tableData[i];
      await modelService.formatModelProperties(projectId, element.instanceId, [
        element.name!,
        element.adornment!,
        element.condition!,
        element.elements!,
        element.priority!
      ]);
    }
    this.loaded = true;
  }

  async handleApply() {
    const action = actionManager.getAction(ActionKey.CreatePropertyModelTreeSelect) as CreatePropertyModelTreeSelect;
    const constraintQueryParams = {
      addMethod: "",
      dataType: PropertyDataType.INSTANCE,
      deleteMethod: "",
      enTips: "",
      isMultiplicity: true,
      key: "Element-constraints",
      name: "",
      readonly: false,
      tips: "",
      updateMethod: "",
      value: [],
      items: [],
      enName: "",
      modelId: this.tabsModel.data.modelId!,
      checkMethod: "checkExcludeConstraintsOnTheElementConstraints",
      moreBtnCondition: "Constraint",
      displayLevel: 3,
      extraInfo: ""
    };

    // toRaw()
    await action?.run(constraintQueryParams);
  }
  getVisibleTableData() {
    let arr = [...this.tableData];
    if (this.sortByNameActive) {
      arr.sort((i, j) => {
        return (i.name?.value as string).localeCompare(j.name?.value as string);
      });
    }

    if (this.searchQuery) {
      const lowerSearchQuery = this.searchQuery.toLowerCase();

      arr = arr.filter(it => {
        const oldName = (it.name?.value as string).toLowerCase() || "";
        return oldName.includes(lowerSearchQuery);
      });
    }

    return arr;
  }

  async loadDataWhenNotLoad() {
    if (!this.loaded) {
      await this.loadData();
    }
  }

  toggleSortByNameActive() {
    this.sortByNameActive = !this.sortByNameActive;
  }
  toggleSearchActive() {
    this.searchActive = !this.searchActive;
  }

  async handleAdd() {
    const { projectId, modelId } = this.tabsModel.data;
    modelService.addModel(projectId!, modelId!, MetaclassType.Constraint, [StType["Customization::LegendItem"]]);
  }

  async handleCopy() {
    const { projectId, modelId } = this.tabsModel.data;
    const row = this.currentRow;
    if (row) {
      loading.delayPopup("正在复制中...");
      try {
        await modelService.pasteNode({
          instanceId: row.instanceId,
          projectId: projectId!,
          targetInstanceId: modelId!,
          targetProjectId: projectId!
        });
        await this.loadData();
        loading.close();
      } catch (e) {
        loading.close();
      }
    }
  }

  async handleDelete() {
    const row = this.currentRow;
    const { projectId, modelId } = this.tabsModel.data;
    if (row) {
      this.deleteLoading = true;
      const prop = await modelService.getModelPropertiesByKey(projectId!, modelId!, PropertyKey.Legend_legendItems);
      propertyUtil.deletePropertyAndRefresh(prop, row.instanceId, projectId);
      this.deleteLoading = false;
    }
  }

  async fresh() {
    await this.loadData();
  }

  async clear() {
    this.tableData = [];
    this.loaded = false;
  }
}
